package com.jay.lang.management.clazz;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryNotificationInfo;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;

import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.openmbean.CompositeData;

import com.jay.lang.clazz.ErrorCls;

public class MemoryNotificationInfoCls {
	public static void main(String[] args) {

		List<MemoryPoolMXBean> mxbeans = ManagementFactory
				.getMemoryPoolMXBeans();
		mxbeans.get(1).setCollectionUsageThreshold(1000l);

		MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
		NotificationEmitter emitter = (NotificationEmitter) mbean;
		MyListener listener = new MyListener();
		emitter.addNotificationListener(listener, null, null);

		ErrorCls[][] e = new ErrorCls[10000][];
		for (int i = 0; i < 10000; i++) {
			e[i] = new ErrorCls[10000];
		}

	}

}

class MyListener implements javax.management.NotificationListener {

	@Override
	public void handleNotification(Notification notif, Object handback) {
		String notifType = notif.getType();
		if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)
				|| notifType
						.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
			// retrieve the memory notification information
			CompositeData cd = (CompositeData) notif.getUserData();
			MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
			System.out.println("Alarm...");
			System.out.println(info);
			System.out.println(info.getPoolName());
			System.out.println(info.getUsage());
		}
	}
}
